﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JQuery.Net.UI;
using System.Collections.ObjectModel;
using System.Web;
using System.Security.Permissions;
using System.Collections;

namespace JQuery.Net.UI
{
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public sealed class MenuItemCollection
        : List<MenuItem>
    {
        private MenuItem menuItem;

        #region constructors
        public MenuItemCollection()
        {
        }

        public MenuItemCollection(MenuItem menuItem)
            : this()
        {
            this.menuItem = menuItem;
        }
        #endregion

        #region properties
        public MenuItem Owner
        {
            get { return menuItem; }
            internal set
            {
                menuItem = value;

                foreach (MenuItem oItem in this)
                {
                    oItem.Parent = Owner;
                    oItem.Container = this;
                }
            }
        }
        #endregion

        #region methods
        public new void Add(MenuItem item)
        {
            if (!Contains(item))
            {
                base.Add(item);

                item.Parent = menuItem;
            }
        }

        public new void AddRange(IEnumerable<MenuItem> oCollection)
        {
            foreach (MenuItem oItem in oCollection)
            {
                Add(oItem);
            }
        }
        #endregion

        public List<MenuItem> GetItemsWithEvents
        {
            get
            {
                return FindItemsWithEvent(this);
            }
        }

        private List<MenuItem> FindItemsWithEvent(MenuItemCollection oItems)
        {
            List<MenuItem> oCollection = new List<MenuItem>();

            foreach (MenuItem oItem in oItems)
            {
                if(oItem.ScriptEvents != null)
                {
                    oCollection.Add(oItem);
                }

                if (oItem.Items.Count > 0)
                {
                    oCollection.AddRange(FindItemsWithEvent(oItem.Items));
                }
            }

            return oCollection;
        }
    }
}
